const express = require('express');
const router = express.Router();
const { body, param, query, validationResult } = require('express-validator');
const Release = require('../models/Release');
const Product = require('../models/Product');
const Translation = require('../models/Translation');
const { uploadToCDN } = require('../services/releaseService');
const { sendWebhook } = require('./webhooks');
const logger = require('../utils/logger');

const validate = (req, res, next) => {
  const errors = validationResult(req);
  if (!errors.isEmpty()) {
    return res.status(400).json({ success: false, errors: errors.array() });
  }
  next();
};

// 创建发布单
router.post('/',
  [
    body('productId').notEmpty().withMessage('产品ID不能为空'),
    body('version').matches(/^\d+\.\d+\.\d+$/).withMessage('版本号格式错误，应为 x.y.z'),
    body('environment').isIn(['development', 'testing', 'production']),
    body('translationIds').optional().isArray(),
  ],
  validate,
  async (req, res, next) => {
    try {
      const { productId, version, environment, translationIds, notes } = req.body;
      
      // 检查产品是否存在
      const product = await Product.findById(productId);
      if (!product) {
        return res.status(404).json({ success: false, message: '产品不存在' });
      }
      
      // 检查版本是否已存在
      const existing = await Release.findOne({ productId, version, environment });
      if (existing) {
        return res.status(409).json({ success: false, message: '该版本已发布' });
      }
      
      // 如果没有指定词条ID，则使用所有已审核的词条
      let ids = translationIds;
      if (!ids || ids.length === 0) {
        const translations = await Translation.find({
          productId,
          status: { $in: ['approved', 'published'] },
          deleted: false
        }).select('_id');
        ids = translations.map(t => t._id);
      }
      
      // 创建发布单
      const release = new Release({
        productId,
        version,
        environment,
        translationIds: ids,
        releasedBy: req.user?.username || 'system',
        notes,
        status: 'pending'
      });
      
      await release.save();
      
      // 异步处理发布
      processRelease(release, product).catch(err => {
        logger.error('发布处理失败', { releaseId: release._id, error: err });
      });
      
      logger.info(`发布单已创建: ${product.name} ${version}`, { environment });
      
      res.status(201).json({
        success: true,
        data: release
      });
    } catch (error) {
      next(error);
    }
  }
);

// 发布处理函数
async function processRelease(release, product) {
  try {
    release.status = 'processing';
    await release.save();
    
    // 获取所有词条
    const translations = await Translation.find({
      _id: { $in: release.translationIds },
      deleted: false
    });
    
    // 生成多语言JSON文件
    const bundles = {};
    product.supportedLocales.forEach(locale => {
      bundles[locale] = {};
      translations.forEach(t => {
        // 处理 locales Map 结构
        let locales = t.locales;
        if (locales instanceof Map) {
          locales = Object.fromEntries(locales);
        } else if (Array.isArray(locales)) {
          // 如果是数组，转换为对象
          locales = Object.fromEntries(locales);
        } else if (!locales || typeof locales !== 'object') {
          locales = {};
        }
        
        const key = t.namespace !== 'common' ? `${t.namespace}.${t.key}` : t.key;
        const value = locales[locale] || locales[product.defaultLocale] || '';
        
        const keys = key.split('.');
        let current = bundles[locale];
        for (let i = 0; i < keys.length - 1; i++) {
          if (!current[keys[i]]) current[keys[i]] = {};
          current = current[keys[i]];
        }
        current[keys[keys.length - 1]] = value;
      });
    });
    
    // 上传到CDN (这里简化处理，实际应调用真实的CDN API)
    const cdnUrls = {};
    for (const [locale, bundle] of Object.entries(bundles)) {
      // 模拟上传到CDN
      const cdnUrl = await uploadToCDN(
        product.code,
        release.version,
        locale,
        bundle
      );
      cdnUrls[locale] = cdnUrl;
    }
    
    // 更新发布单
    release.bundleUrls = new Map(Object.entries(cdnUrls));
    release.status = 'success';
    await release.save();
    
    // 更新产品环境配置
    product.environments[release.environment] = {
      version: release.version,
      cdnUrl: cdnUrls[product.defaultLocale] // 使用默认语言的CDN URL作为基础URL
    };
    await product.save();
    
    // 触发Webhook通知产品方
    if (product.webhookUrl) {
      try {
        await sendWebhook(product.webhookUrl, 'release.published', {
          productCode: product.code,
          version: release.version,
          environment: release.environment,
          bundleUrls: Object.fromEntries(cdnUrls)
        });
        logger.info('Webhook通知已发送', { productId: product._id, releaseId: release._id });
      } catch (error) {
        logger.error('Webhook发送失败', { error: error.message, productId: product._id });
        // Webhook失败不影响发布流程
      }
    }
    
    logger.info(`发布成功: ${product.name} ${release.version}`, { environment: release.environment });
  } catch (error) {
    release.status = 'failed';
    release.errorMessage = error.message;
    await release.save();
    throw error;
  }
}

// 查询发布列表
router.get('/',
  [
    query('productId').optional(),
    query('environment').optional().isIn(['development', 'testing', 'production']),
  ],
  validate,
  async (req, res, next) => {
    try {
      const { productId, environment } = req.query;
      const filter = {};
      if (productId) filter.productId = productId;
      if (environment) filter.environment = environment;
      
      const releases = await Release.find(filter)
        .populate('productId', 'name code')
        .sort({ createdAt: -1 })
        .limit(50);
      
      res.json({
        success: true,
        data: releases.map(r => ({
          ...r.toObject(),
          bundleUrls: Object.fromEntries(r.bundleUrls || [])
        }))
      });
    } catch (error) {
      next(error);
    }
  }
);

module.exports = router;

